package com.base.web.socket.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.base.common.sys.entity.SysUserEntity;
import com.base.common.sys.service.SysUserService;
import com.base.common.utils.R;

@RequestMapping("/sys")
@Controller
public class SysUserController {

	@Resource
	private SysUserService sysUserService;
	
	/**
	 * 登录用户，账号不存在就注册
	 * @param entity
	 * @return
	 */
	@PostMapping("/login")
	@ResponseBody
	public R login(SysUserEntity entity, HttpServletRequest request) {
		if(StringUtils.isBlank(entity.getUsername()) || StringUtils.isBlank(entity.getPassword())) {
			return R.error("请输入账号和密码！");
		}
		SysUserEntity user = sysUserService.login(entity);
		if(null == user) {
			entity.setStatus(1);
			entity.setName(entity.getUsername());
			sysUserService.insert(entity); //新增返回主键
			user = entity;
		}
		if(null == user.getId()) {
			return R.error("登录失败！");
		}
		request.getSession().setAttribute("userId", user.getId());
		request.getSession().setAttribute("username", user.getName());
		return R.ok().put("userId", user.getId());
	}
	
	/**
	 * 获取用户列表
	 * @param userId
	 * @return
	 */
	@GetMapping("/findUserList")
	@ResponseBody
	public R getUserList(Integer userId) {
		List<SysUserEntity> list = sysUserService.findByEntity(new SysUserEntity());
		SysUserEntity rme = null;
		for (int i = 0; i < list.size(); i++) {
			if(list.get(i).getId().equals(userId)) {
				rme = list.get(i);
			}
		}
		if(null != rme) {
			list.remove(rme);
		}
		return R.ok().put("userList", list);
	}
	
	/**进入聊天室*/
	@GetMapping("/toChatHome")
	public String toChatHome(Integer userId, Model model) {
		SysUserEntity user = sysUserService.findById(userId);
		model.addAttribute("user", user);
		
		System.out.println("进入聊天室");
		return "chat-home";
	}
	
	@GetMapping("/to/{view}")
	public ModelAndView home(@PathVariable String view) {
		return new ModelAndView(view);
	}
}
